<template>
  <div class="c-bg-sgray">
    <div class="c-w100 c-hh60 theme-bg-10 c-ph24 c-flex-row c-aligni-center">
      <i class="iconfont icon-laba theme-fc c-pr16"></i>
      <p class="theme-fc c-fs22">订单仅支持修改一次，敬请谅解~</p>
    </div>
    <div class="c-bg-white c-mt10 c-ph24">
      <div class="c-flex-row c-aligni-center c-justify-sb c-hh88 c-bd-b1">
        <span class="c-fs26 c-fc-xblack c-fw600">修改收货人信息</span>
        <div class="c-fc-xblack c-fs24" @click="showAddressModal()" v-if="addressList && addressList.length > 1">
          <i class="iconfont">&#xe6f1;</i>
          <span>切换地址</span>
        </div>
      </div>
      <div class="c-flex-row c-aligni-center c-hh88 c-bd-b1">
        <span class="c-fs26 c-fc-sblack c-ww150">收件人</span>
        <input type="text" v-model="addressInfo.name" class="input-right c-fs28 c-flex-grow1 c-w0  c-fc-xblack" placeholder="收件人">
      </div>
      <div class="c-flex-row c-aligni-center c-hh88 c-bd-b1">
        <span class="c-fs26 c-fc-sblack c-ww150">联系电话</span>
        <input type="text" v-model="addressInfo.mobile" class="input-right c-fs28 c-flex-grow1 c-w0  c-fc-xblack" placeholder="联系电话">
      </div>
      <div class="c-flex-row c-aligni-center c-hh88 c-bd-b1">
        <span class="c-fs26 c-fc-sblack c-ww150">所在地区</span>
        <div class="c-flex-row c-flex-grow1 c-w0 c-fs28  c-fc-xblack picker-address">
          <x-address :themeColor="$getThemeColor()" value-text-align='left' title="" v-model="addrValue" :list="addressData" raw-value placeholder="请选择地址" :show.sync="showAddress" class="c-flex-grow1"></x-address>
        </div>
      </div>
      <div class="c-flex-row c-aligni-center c-hh88 c-bd-b1">
        <span class="c-fs26 c-fc-sblack c-ww150">详细地址</span>
        <input type="text" v-model="addressInfo.address" class="input-right c-fs28 c-flex-grow1 c-w0  c-fc-xblack" placeholder="街道、楼牌号等">
      </div>
    </div>
    <div class="c-w100 c-maxw640 c-hh100 c-pf c-p-b0 c-flex-row c-aligni-center c-ph24">
      <div class="c-w100 c-hh64 c-fc-white c-fs28 c-flex-row c-flex-center c-br36 theme-bg" @click="handleClickAddress()">确认修改</div>
    </div>
    <open-modal :openModal="openAddressModal" @closeModal="closeAddressModal">
      <div class="c-bg-white c-br-tl8 c-br-tr8 c-pr24 c-pl24 c-maxh356">
        <div class="c-flex-row c-aligni-center c-justify-center c-w100 c-hh80 c-fs26 c-fc-xblack">收货地址</div>
        <div class="c-flex-column c-aligni-center address_contain" id="scrollContent" @scroll="scrollContent($event)">
          <div class="address_item c-ph24 c-p c-pv20 c-br20 c-w100 c-mt10" :class="[cur == index ? 'c-bd2-FF7100 active' : 'c-bd2-f5f5f5']" v-for="(item, index) in addressList" :key="item.addrId" @click="handleClickSelectAddress(item, index)">
            <div class="c-fs24 c-fc-xblack c-mb10">
              <span>{{item.name}}</span>
              <span class="c-pl20">{{item.mobile}}</span>
            </div>
            <div class="c-fs20 c-fc-sblack">
              <span>地址：{{item.province}}{{item.city}}{{item.area}}{{item.address}}</span>
            </div>
            <div class="address_icon" :class="{active:cur===index}"></div>
          </div>
          <loading-status-tem id="loading" :dataStatus="dataStatus" noDataText="暂无收货地址"></loading-status-tem>
        </div>
      </div>
    </open-modal>
  </div>
</template>

<script>
  import { XAddress } from 'ckjrweb-mp-ui/src/components/index';
  import { utilJs } from "@/utils/common.js";
  import loadingStatusTem from "@/components/templates/common/loadingStatusTem.vue";
  import openModal from "@/components/templates/common/openModal.vue";
  import { mapState } from 'vuex';
  let isClickIng = false;
  let pageIndex = 1;
  let isFromOrderList = false; // 判断是否是商城订单列表页面进入
  let isFromAllOrderList = false; // 判断是否是订单列表页面进入
  export default {
    name: 'OrderAddress',
    components: {
      XAddress,
      openModal,
      loadingStatusTem
    },
    data() {
      return {
        theme: localStorage.getItem("colorName") ? localStorage.getItem("colorName") : "mb5_default",
        addressInfo: {
          no: 1,
          name: '',
          mobile: '',
          provinceId: "",
          cityId: "",
          areaId: "",
          address: '',
          postcode: "",
          addressId: "",
          isDefult: true
        },
        addressList: [],
        addrValue: [],
        showAddress: false,
        addressData: [],
        openAddressModal: false,
        dataStatus: 'HAS_MORE_DATA',
        cur: -1,
        canscroll: true,
        goId: ''
      }
    },
    computed: {
      ...mapState({
        orderList: state => state.oem_store.orderList,
        allOrderList: state => state.oem_store.allOrderList
      }),
    },
    beforeRouteEnter(to, from, next) {
      if (from.path == '/mall/mallOrder/orderList') {
        isFromOrderList = true;
      } else if (from.path == '/member/myOrder/allOrderList') {
        isFromAllOrderList = true;
      } else if (from.path == '/mall/mallOrder/orderDetail') {
        isFromOrderList = true;
        isFromAllOrderList = true;
      }
      next();
    },
    created() {
      utilJs.appShare(this);
    },
    activated() {
      setDocumentTitle("修改地址");// eslint-disable-line
      this.goId = this.$route.query.goId;
      isClickIng = false;
      pageIndex = 1;
      this.cur = -1;
      this.addressInfo = {
        no: 1,
        name: '',
        mobile: '',
        provinceId: "",
        cityId: "",
        areaId: "",
        address: '',
        addressId: '',
        postcode: "",
        isDefult: true
      };
      this.addressList = [];
      this.addrValue = [];
      this.showAddress = false;
      this.addressData = [];
      this.getAreaListForAgent();
      this.getAddressList();
      this.getUserAddress();
      this.wechatShare();
    },
    methods: {
      getUserAddress() {
        utilJs.getMethod(global.apiurl + "goodsOrders/getUserAddress?goId=" + this.goId, res => {
          this.addressInfo = {
            no: 1,
            name: res.userName,
            mobile: res.userMobile,
            provinceId: res.provinceId,
            cityId: res.cityId,
            areaId: res.areaId,
            address: res.address,
            addressId: res.userAddressId,
            postcode: '',
            isDefult: true
          }
          if (!res.provinceId && !res.cityId && !res.areaId) {
            this.addrValue = [];
          } else {
            this.addrValue = [
              "" + res.provinceId,
              "" + res.cityId,
              "" + res.areaId
            ];
          }
        },
          failRes => {
          });
      },
      scrollContent(event) {
        if (this.canscroll) {
          let scroll = event.target.scrollTop;
          let scrollListH = document.getElementById("scrollList").clientHeight;
          let scrollContentH = event.target.clientHeight;
          let loadingH = document.getElementById("loading").clientHeight;
          if (scrollListH - (scroll + scrollContentH + loadingH) >= 0) {
            this.canscroll = false; //锁定滚动触发条件
            this.getAddressList();
          }
        }
      },
      handleClickSelectAddress(item, index) {
        this.cur = index;
        this.addressInfo = {
          no: 1,
          name: item.name,
          mobile: item.mobile,
          provinceId: item.provinceId,
          cityId: item.cityId,
          areaId: item.areaId,
          address: item.address,
          addressId: item.addrId,
          postcode: '',
          isDefult: true
        }
        this.addrValue = [
          "" + item.provinceId,
          "" + item.cityId,
          "" + item.areaId
        ];
        this.openAddressModal = false;
      },
      showAddressModal() {
        this.openAddressModal = true;
      },
      closeAddressModal() {
        this.openAddressModal = false;
      },
      handleClickAddress() {
        if (isClickIng) {
          return true;
        }
        if (!this.checkAddressInfo()) {
          return true;
        }
        isClickIng = true;
        let _this = this;
        let saveData = {
          goId: _this.goId,
          userAddressId: _this.addressInfo.addressId,
          name: _this.addressInfo.name,
          mobile: _this.addressInfo.mobile,
          provinceId: _this.addrValue.length > 0 ? _this.addrValue[0] : "",
          cityId: _this.addrValue.length > 1 ? _this.addrValue[1] : "",
          areaId: _this.addrValue.length > 2 ? _this.addrValue[2] : "",
          address: _this.addressInfo.address,
        };
        utilJs.postMethod(global.apiurl + "goodsOrders/changeUserAddress", saveData, res => {
          if (res.isUpdate == 0) {
            isClickIng = false;
            _this.$router.go(-1);
            return
          }
          _this.$showCjToast({
            text: "修改地址成功",
            type: "success",
          }).then(() => {
            _this.updateStore();
            _this.$router.go(-1);
          });
        }, failRes => {
          isClickIng = false;
        });
      },
      updateStore() {
        if (isFromOrderList) {
          let orderList = this.orderList;
          orderList.forEach((item, index) => {
            if (item.goId == this.goId) {
              this.$set(orderList[index], 'updateAddressTime', 1)
            }
          })
          this.$store.commit('updateOrderList', orderList);
          isFromOrderList = false;
        }
        if (isFromAllOrderList) {
          let allOrderList = this.allOrderList;
          allOrderList.forEach((item, index) => {
            if (item.goId == this.goId) {
              this.$set(allOrderList[index], 'updateAddressTime', 1)
            }
          })
          this.$store.commit('updateAllOrderList', allOrderList);
          isFromAllOrderList = false;
        }
      },
      //获取地址列表
      getAddressList() {
        if (this.dataStatus == 'LOADING') {
          return;
        }
        this.dataStatus = 'LOADING';
        utilJs.getMethod(global.apiurl + "address?page=" + pageIndex, res => {
          if (pageIndex == 1) {
            this.addressList = res.address.data;
          } else {
            this.addressList = [...this.addressList, ...res.address.data];
          }
          if (res.address.to * 1 == res.address.total * 1) {
            this.dataStatus = res.address.total * 1 == 0 ? 'NO_DATA' : 'NO_MORE_DATA';
            if (this.dataStatus == 'NO_MORE_DATA') {
              this.canscroll = false;
            }
          } else {
            this.dataStatus = 'HAS_MORE_DATA';
            pageIndex++;
            this.canscroll = true;
          }
        },
          failRes => {
            this.dataStatus = 'DATA_ERROR';
          });
      },
      checkAddressInfo() {
        if (!this.addressInfo.name) {
          this.$showCjToast({
            text: "收货人姓名不能为空",
            type: "warn",
          });
          return false;
        } else if (!utilJs.isPhoneNumber(this.addressInfo.mobile)) {
          this.$showCjToast({
            text: "请输入正确的手机号",
            type: "warn",
          });
          return;
        } else if (this.addrValue.length <= 0) {
          this.$showCjToast({
            text: "收货人地址不能为空",
            type: "warn",
          });
          return false;
        } else if (!this.addressInfo.address) {
          this.$showCjToast({
            text: "收货人详细地址不能为空",
            type: "warn",
          });
          return false;
        }
        return true;
      },
      getAreaListForAgent() {
        utilJs.getMethod(`${global.apiurl}common/getAreaListForAgent`, res => {
          this.addressData = res.data;
        }, failRes => {
        });
      },
      wechatShare: function () {
        let shareUrl =
          window.location.href.split("#")[0] +
          "#/?refereeId=" +
          localStorage.getItem("userId");
        utilJs.wechatConfig(shareUrl, "", "", "", function () { });
      },
      appShare: function () {
        var shareUrl =
          window.location.href.split("#")[0] +
          "#/?refereeId=" +
          localStorage.getItem("userId");
        utilJs.appShareTrue("", "", shareUrl, "");
      }
    }
  }
</script>

<style lang="less" scoped>
.address_contain {
  max-height: 6.25rem;
  overflow: auto;
}
.address_item {
  box-shadow: 0px 4px 12px 0px rgba(204,204,204,0.20);
  .address_icon {
    display: none;
    position: absolute;
    right: 0;
    bottom: -1px;
    width: 1.2rem;
    height: 1.2rem;
    background: url("../../../assets/addres_btn.png") no-repeat center center;
    background-size: contain;
    &.active {
      display: block;
    }
  }
}
.c-bd2-f5f5f5 {
  border: 2px solid #f5f5f5;
}
.c-bd2-FF7100 {
  border: 2px solid #FF7100;
}
.c-maxh356 {
  max-height: 8.9rem;
  overflow: hidden;
}
.input-right {
  height: 100%;
  border: 0;
  background: none;
  outline: none;
}
.input-right:focus {
  outline: none;
}
</style>